#include "root.h"

static int Rs485Mutex = -1;

static void Rs485Lock(int port)
{	
	os_smlock(Rs485Mutex);
}

static void Rs485Unlock(int port)
{	
	os_smunlock(Rs485Mutex);
}

int Rs485_DirTx(int port)
{
	switch(port)
	{
		case UART5_RS485:
			GPIO_WriteBit(HT_GPIOC, PC6_RTS5, Bit_SET);	
			break;
		case UART3_CZ:
			GPIO_WriteBit(HT_GPIOE, PE3_RTS3, Bit_SET); 
			break;			
		default:
			break;
	}
	
	return 0;
}
int Rs485_DirRx(int port)
{
	switch(port)
	{
		case UART5_RS485:
			GPIO_WriteBit(HT_GPIOC, PC6_RTS5, Bit_RESET); 
			break;
		case UART3_CZ:
			GPIO_WriteBit(HT_GPIOE, PE3_RTS3, Bit_RESET); 
			break;			
		default:
			break;
	}	
	return 0;
}

int Rs485Init(void)
{
	Rs485Mutex = os_smcreate(1);
	Rs485_DirRx(UART5_RS485);
	Rs485_DirRx(UART3_CZ);

	return 0;
}

int Rs485IGetChar(unsigned char *buf)
{
	if(UART_Recv(UART5_RS485, buf, 1) > 0)
	{
		//print_charbuf(buf, 1);
		return 0;
	}
	return 1;
}

int Rs485IRawSend(unsigned char *buf, int len)
{
	int ret;
	
	Rs485_DirTx(UART5_RS485);
	Rs485Lock(0);
	ret = UART_Send(UART5_RS485, (UCHAR *)buf, len);	
	Rs485Unlock(0);
	return ret;
}
int CardUartGetchar(unsigned char *buf)
{
	if(UART_Recv(UART2_CS, buf, 1) > 0)
	{
		return 0;
	}
	return 1;
}

int CardUartRawSend(unsigned char *buf,int len)
{
	int ret;
	
	ret = UART_Send(UART2_CS, (UCHAR *)buf, len);	
	return ret;

}

int CzUartRawSend(unsigned char *buf,int len)
{
	int ret;	
	Rs485_DirTx(UART3_CZ);
	ret = UART_Send(UART3_CZ, (UCHAR *)buf, len);	
	return ret;
}

int CzUartGetchar(unsigned char *buf)
{
	if(UART_Recv(UART3_CZ, buf, 1) > 0)
	{
		return 0;
	}
	return 1;
}
int LcdUartRawSend(unsigned char *buf,int len)
{
	int ret;
	
	ret = UART_Send(UART0_LCD, (UCHAR *)buf, len);	
	return ret;
}
int LcdartGetchar(unsigned char *buf)
{
	if(UART_Recv(UART0_LCD, buf, 1) > 0)
	{
	
		return 0;
	}
	return 1;
}
int DebugUartRawSend(unsigned char *buf,int len)
{
	int ret;
	
	ret = UART_Send(UART1_DEBUG, (UCHAR *)buf, len);	
	return ret;

}
int DebugUartGetchar(unsigned char *buf)
{
	if(UART_Recv(UART1_DEBUG, buf, 1) > 0)
	{
		return 0;
	}
	
	return 1;

}

int shell_rs485test(void)
{
	return 0;
}
